package com.paso.springbootsecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import javax.annotation.security.PermitAll;

/**
 * @Classname: WebSecutiryConfig
 * @Description: Secutiry相关配置在这里
 * @Date: 2021/2/21 23:44
 * @Created: by Wang Xu
 */
@EnableWebSecurity
public class WebSecutiryConfig extends WebSecurityConfigurerAdapter {


    // 密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
//        return new NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }


    // ********最重要的就是*********** 安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 关闭跨站请求限制
        http.csrf().disable()
                .authorizeRequests()
                .mvcMatchers("/r/r1").hasAnyAuthority("p1")
                .mvcMatchers("/r/r2").hasAnyAuthority("p2")
//                .mvcMatchers("/r/**").authenticated() // 所有/r/**的请求必须认证通过
                .mvcMatchers("/**").authenticated() // 所有/**的请求必须认证通过
                .anyRequest().permitAll() // 其他的请求可以访问
                .and()
                .formLogin() // 允许表单登录
                .loginPage("/login-view")//指定我们自己的登录页面.springsecurity已重定向方式定位到/login-view
                .loginProcessingUrl("/login")// 指定登录处理的URL，也就是用户名、密码表单提交的目的路径
                .successForwardUrl("/login-success")// 登录成功后跳转的页面
                .permitAll();//允许任意用户访问基于表单登录的所有URL

    }

}
